﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RMS.DB
{
    class LicenseInfoManager : DBController
    {
        public bool CheckLicenseInfo(License license)
        {
            if (license == null)
            {
                License info = GetOne();
                if (info != null && info.LicenseKey.Equals(Common.Utilities.Lisence(Common.Utilities.ProcessorID())))
                {
                    return true;
                }
            }
            else
            {
                if (license.LicenseKey.Equals(Common.Utilities.Lisence(Common.Utilities.ProcessorID())))
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Get an instance of Shop Info
        /// </summary>
        /// <returns></returns>
        public License GetOne()
        {
            try
            {
                var query = from shops in DataEntities.License
                            select shops;

                return query.FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.Msg.ConnectError);
            }
        }

        /// <summary>
        /// Save instance
        /// </summary>
        /// <param name="license"></param>
        /// <returns></returns>
        private int Save(License license)
        {
            try
            {
                DataEntities.AddToLicense(license);
                return DataEntities.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.Msg.ConnectError);
            }
        }

        /// <summary>
        /// Update Shop info instance = Delete all + Save new one
        /// </summary>
        /// <param name="license"></param>
        /// <returns></returns>
        public int Update(License license)
        {
            //Delete all old items
            int deleteResult = DeleteAll();
            
            return Save(license);          

           
        }

        /// <summary>
        /// Delete all records
        /// </summary>
        /// <returns></returns>
        public int DeleteAll()
        {
            try
            {
                var list = from shops in DataEntities.License
                           select shops;

                if (list != null && list.Count() > 0)
                    foreach (var item in list)
                    {
                        DataEntities.DeleteObject(item);
                    }

                return DataEntities.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.Msg.ConnectError);
            }
        }
    }
}
